Skip to content

Implement the when expression#21

Merged
hexaredecimal merged 3 commits intomainfrom
Sibusiso
May 20, 2025
Merged

Implement the when expression#21
hexaredecimal merged 3 commits intomainfrom
Sibusiso

Conversation

@hexaredecimal
Copy link
Copy Markdown
Collaborator

@hexaredecimal hexaredecimal commented May 19, 2025

I have implemented the when expression (#20) and added the first tests using junit5.

Summary by CodeRabbit

  • New Features
    • Enhanced pattern matching capabilities, including support for identifiers, literals, tuples, arrays, list constructors, and objects.
  • Bug Fixes
    • Improved error messaging for pattern matching failures.
  • Tests
    • Added comprehensive tests for parsing and AST construction of functions, variables, modules, and imports.
    • Introduced runtime tests to verify correct execution of functions, variables, and module imports.
  • Refactor
    • Updated visibility of internal data structures in arrays, tuples, and objects for improved accessibility.

@hexaredecimal hexaredecimal added this to the Road to 1.0 milestone May 19, 2025
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented May 19, 2025

Walkthrough

The changes introduce advanced pattern matching capabilities in the WhenAst class, enabling recursive structural matching for various data types. Field visibility is updated to public for internal collections in array, tuple, and object runtime classes. Two new test classes are added to validate AST parsing and runtime behaviors, covering functions, variables, modules, and imports. Additionally, minor package and import adjustments were made in editor-related classes.

Changes

File(s) Change Summary
src/main/java/org/piccode/ast/WhenAst.java Enhanced pattern matching in WhenAst with recursive matching logic and symbol table management. Improved error message wording.
src/main/java/org/piccode/rt/PiccodeArray.java
src/main/java/org/piccode/rt/PiccodeTuple.java
Changed visibility of nodes field from private to public in both array and tuple runtime classes.
src/main/java/org/piccode/rt/PiccodeObject.java Changed visibility of obj field from private to public in the object runtime class.
src/test/java/org/piccode/ast/TopLevel.java Added new test class for AST parsing: tests function, variable, module, and import statement parsing and AST structure validation.
src/test/java/org/piccode/rt/Runtime.java Added new test class for runtime: tests function execution, variable declaration, and import statement execution.
src/main/java/org/editor/EditorWindow.java Added import for DockablePanel from org.editor.panels.
src/main/java/org/editor/panels/DockablePanel.java Changed package declaration from org.editor to org.editor.panels.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant WhenAst
    participant SymbolTable
    participant Context
    participant Case

    User->>WhenAst: execute()
    WhenAst->>Context: get current scope
    loop for each case
        WhenAst->>SymbolTable: create temporary symbol table
        WhenAst->>WhenAst: isMatching(patterns, cond_value, temp)
        alt pattern matches
            WhenAst->>Context: push temp bindings to local scope
            WhenAst->>Case: execute matched case
            WhenAst->>Context: drop stack frame
            WhenAst-->>User: return result
        end
    end
    WhenAst-->>User: throw inexhaustive error
Loading

Poem

In the warren of code, new patterns appear,
Matching arrays, tuples, with logic so clear.
Objects and lists, all bound with delight,
Public fields shining, no more hidden from sight.
With tests now in place, our scripts hop ahead—
The rabbit approves, with a twitch of its head!
🐇✨

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 0da76a9 and 102a725.

📒 Files selected for processing (2)
  • src/main/java/org/editor/EditorWindow.java (1 hunks)
  • src/main/java/org/editor/panels/DockablePanel.java (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • src/main/java/org/editor/EditorWindow.java
  • src/main/java/org/editor/panels/DockablePanel.java
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@hexaredecimal hexaredecimal self-assigned this May 19, 2025
@hexaredecimal hexaredecimal added the enhancement New feature or request label May 19, 2025
@hexaredecimal
Copy link
Copy Markdown
Collaborator Author

@MlaumeCasa @Matuku45 Awaiting code approval.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🧹 Nitpick comments (12)
src/main/java/org/piccode/rt/PiccodeArray.java (1)

12-12: Consider encapsulation implications of public field

While making nodes public enables direct access needed for pattern matching in the "when" expression implementation, it breaks encapsulation. Consider alternatives like making the field final to prevent reassignment while maintaining the required accessibility.

-	public List<PiccodeValue> nodes;
+	public final List<PiccodeValue> nodes;
src/main/java/org/piccode/rt/PiccodeTuple.java (1)

12-12: Consider encapsulation implications of public field

Similar to the change in PiccodeArray, making nodes public breaks encapsulation principles. Consider making the field final to prevent reassignment while maintaining the accessibility needed for pattern matching in the "when" expression.

-	public List<PiccodeValue> nodes;
+	public final List<PiccodeValue> nodes;
src/main/java/org/piccode/rt/PiccodeObject.java (1)

13-13: Consider encapsulation implications of public field

Similar to other runtime classes, making obj public breaks encapsulation principles. Consider making the field final to at least prevent reassignment of the HashMap reference while maintaining the accessibility needed for pattern matching operations.

-	public HashMap<String, PiccodeValue> obj;
+	public final HashMap<String, PiccodeValue> obj;
src/test/java/org/piccode/ast/TopLevel.java (5)

26-26: Simplify assertion for better readability

The negated assertion can be simplified using a more direct positive assertion method.

-		assertFalse(!(func instanceof FunctionAst));
+		assertTrue(func instanceof FunctionAst);

41-41: Simplify assertion for better readability

The negated assertion can be simplified using a more direct positive assertion method.

-		assertFalse(!(let instanceof VarDecl));
+		assertTrue(let instanceof VarDecl);

60-60: Simplify assertion for better readability

The negated assertion can be simplified using a more direct positive assertion method.

-		assertFalse(!(mod instanceof ModuleAst));
+		assertTrue(mod instanceof ModuleAst);

75-75: Simplify assertion for better readability

The negated assertion can be simplified using a more direct positive assertion method.

-		assertFalse(!(import_ instanceof ImportAst));
+		assertTrue(import_ instanceof ImportAst);

44-44: Enhance pattern match test clarity

The pattern matching assertion uses a compact form that's harder to read. Consider breaking it into multiple assertions for better clarity and failure diagnostics.

-		assertTrue(node.value instanceof NumberAst num && num.text.equals("1"));
+		assertTrue(node.value instanceof NumberAst);
+		NumberAst num = (NumberAst) node.value;
+		assertEquals("1", num.text);
src/test/java/org/piccode/rt/Runtime.java (3)

5-8: Remove unused / redundant imports

AccessFrame is not referenced, and Assertions is redundant with the static import of the assertion methods. Keeping them adds noise and may trigger “unused-import” compiler warnings.

-import org.editor.AccessFrame;
-import org.junit.jupiter.api.Assertions;
+// (no changes needed – simply delete the two lines above)

28-29: Replace double negatives with direct assertTrue

assertFalse(!(expr)) is harder to read than assertTrue(expr).

-assertFalse(!(func instanceof FunctionAst));
+assertTrue(func instanceof FunctionAst);

Make the analogous change for the VarDecl and ImportAst assertions.

Also applies to: 41-42, 55-56


19-19: Avoid shadowing java.lang.Runtime

Naming the test class Runtime can confuse tooling and readers because it shadows java.lang.Runtime. Consider renaming to RuntimeTest.

src/main/java/org/piccode/ast/WhenAst.java (1)

79-87: Avoid re-executing literal ASTs

lit.execute() allocates a new PiccodeValue each time, which is unnecessary and may break reference-based equality semantics.
Consider caching the literal’s value once during AST construction or comparing the literal’s raw token text.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 44c0401 and 0da76a9.

📒 Files selected for processing (6)
  • src/main/java/org/piccode/ast/WhenAst.java (3 hunks)
  • src/main/java/org/piccode/rt/PiccodeArray.java (1 hunks)
  • src/main/java/org/piccode/rt/PiccodeObject.java (1 hunks)
  • src/main/java/org/piccode/rt/PiccodeTuple.java (1 hunks)
  • src/test/java/org/piccode/ast/TopLevel.java (1 hunks)
  • src/test/java/org/piccode/rt/Runtime.java (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
src/main/java/org/piccode/ast/WhenAst.java (1)
src/main/java/org/piccode/rt/Context.java (1)
  • Context (10-49)
src/test/java/org/piccode/rt/Runtime.java (2)
src/main/java/org/editor/errors/IDEErrorListener.java (1)
  • IDEErrorListener (12-39)
src/main/java/org/piccode/rt/Context.java (1)
  • Context (10-49)
🔇 Additional comments (1)
src/test/java/org/piccode/ast/TopLevel.java (1)

18-80: Consider testing the new "when" expression feature

Since this PR is implementing the "when" expression feature, it would be beneficial to include test cases specifically for this new functionality to ensure it works correctly with different patterns and conditions.

Could you add test cases that verify the parsing and AST generation for the "when" expression? This would ensure the feature is properly implemented and avoid potential regressions in the future.

Comment on lines +81 to +94
private static StatementList compile(String code) {
var lexer = new PiccodeScriptLexer(CharStreams.fromString(code));
var parser = new PiccodeScriptParser(new CommonTokenStream(lexer));
lexer.removeErrorListeners();
parser.removeErrorListeners();

IDEErrorListener errorListener = new IDEErrorListener();
lexer.addErrorListener(errorListener);
parser.addErrorListener(errorListener);

var visitor = new PiccodeVisitor();

return (StatementList) visitor.visit(parser.stmts());
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

The compile method should handle exceptions gracefully

The compile method doesn't catch or handle potential exceptions that might occur during parsing. This could cause tests to fail with unhelpful stack traces rather than meaningful assertion failures.

Consider adding exception handling to provide more informative test failures:

 	private static StatementList compile(String code) {
+		try {
 		var lexer = new PiccodeScriptLexer(CharStreams.fromString(code));
 		var parser = new PiccodeScriptParser(new CommonTokenStream(lexer));
 		lexer.removeErrorListeners();
 		parser.removeErrorListeners();

 		IDEErrorListener errorListener = new IDEErrorListener();
 		lexer.addErrorListener(errorListener);
 		parser.addErrorListener(errorListener);

 		var visitor = new PiccodeVisitor();

 		return (StatementList) visitor.visit(parser.stmts());
+		} catch (Exception e) {
+			fail("Failed to compile code: " + code + " - " + e.getMessage());
+			return null; // This line won't be reached due to fail() above
+		}
 	}
🤖 Prompt for AI Agents
In src/test/java/org/piccode/ast/TopLevel.java around lines 81 to 94, the
compile method lacks exception handling for parsing errors, which can lead to
uninformative test failures. Wrap the parsing and visiting logic in a try-catch
block that catches relevant exceptions, then throw a runtime exception or
assertion error with a clear, descriptive message to improve test failure
diagnostics.

var code = "function add(x, y) = x + y";
var ast = compile(code);

assertEquals(ast.nodes.size(), 1);
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Swap expected/actual arguments in assertEquals

JUnit’s signature is assertEquals(expected, actual). Inverting the order can produce misleading failure messages.

-assertEquals(ast.nodes.size(), 1);
+assertEquals(1, ast.nodes.size());

Apply the same change in the other two occurrences.

Also applies to: 38-38, 53-53

🤖 Prompt for AI Agents
In src/test/java/org/piccode/rt/Runtime.java at lines 25, 38, and 53, the
arguments to assertEquals are reversed; JUnit expects the first argument to be
the expected value and the second to be the actual value. Swap the arguments in
these three lines so that the expected value comes first and the actual value
second to ensure accurate failure messages.

Comment on lines +66 to +69
IDEErrorListener errorListener = new IDEErrorListener();
lexer.addErrorListener(errorListener);
parser.addErrorListener(errorListener);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Check and assert on syntax errors during compilation

An IDEErrorListener is attached but its collected errors are ignored.
Add a post-parse assertion to fail fast when the input code contains syntax errors.

var visitor = new PiccodeVisitor();
var stmtList = (StatementList) visitor.visit(parser.stmts());

+assertTrue(errorListener.getSyntaxErrorInfos().isEmpty(),
+        () -> "Unexpected syntax errors: " + errorListener.getSyntaxErrorInfos());
+
return stmtList;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
IDEErrorListener errorListener = new IDEErrorListener();
lexer.addErrorListener(errorListener);
parser.addErrorListener(errorListener);
var visitor = new PiccodeVisitor();
var stmtList = (StatementList) visitor.visit(parser.stmts());
assertTrue(errorListener.getSyntaxErrorInfos().isEmpty(),
() -> "Unexpected syntax errors: " + errorListener.getSyntaxErrorInfos());
return stmtList;
🤖 Prompt for AI Agents
In src/test/java/org/piccode/rt/Runtime.java around lines 66 to 69, the
IDEErrorListener is added to the lexer and parser but its collected syntax
errors are not checked. After parsing, add an assertion to check if the
errorListener has recorded any syntax errors and fail the test immediately if
errors exist, ensuring the compilation process fails fast on invalid input.

Comment on lines +138 to +139
return true;
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Array pattern matches even when the pattern is non-empty

The catch-all branch accepts any ArrayAst pattern whenever the value is an empty list, regardless of whether the pattern itself has elements, resulting in incorrect matches.

Add a check that the pattern contains zero elements:

-if (pattern instanceof ArrayAst && value instanceof PiccodeArray vList && vList.nodes.isEmpty()) {
-    return true;
+if (pattern instanceof ArrayAst arrPat
+        && value instanceof PiccodeArray vList
+        && arrPat.nodes.isEmpty()
+        && vList.nodes.isEmpty()) {
+    return true;
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
return true;
}
if (pattern instanceof ArrayAst arrPat
&& value instanceof PiccodeArray vList
&& arrPat.nodes.isEmpty()
&& vList.nodes.isEmpty()) {
return true;
}
🤖 Prompt for AI Agents
In src/main/java/org/piccode/ast/WhenAst.java at lines 138-139, the code
currently returns true for any ArrayAst pattern when the value is an empty list,
even if the pattern is non-empty. To fix this, add a condition to check that the
pattern's element count is zero before returning true, ensuring only empty
patterns match empty lists.

Comment on lines +44 to +53
var tempSymtable = new HashMap<String, PiccodeValue>();
if (isMatching(match_case.match, cond_value, tempSymtable)) {
Context.top.pushStack();
for (var entry : tempSymtable.entrySet()) {
Context.top.putLocal(entry.getKey(), entry.getValue());
}
var result = match_case.value.execute();
Context.top.dropStackFrame();
return result;
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Ensure stack-frame cleanup with try/finally

If match_case.value.execute() throws, dropStackFrame() is skipped, leaking the pushed scope and corrupting subsequent evaluation.

-Context.top.pushStack();
-for (var entry : tempSymtable.entrySet()) {
-    Context.top.putLocal(entry.getKey(), entry.getValue());
-}
-var result = match_case.value.execute();
-Context.top.dropStackFrame();
-return result;
+Context.top.pushStack();
+try {
+    for (var entry : tempSymtable.entrySet()) {
+        Context.top.putLocal(entry.getKey(), entry.getValue());
+    }
+    return match_case.value.execute();
+} finally {
+    Context.top.dropStackFrame();
+}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
var tempSymtable = new HashMap<String, PiccodeValue>();
if (isMatching(match_case.match, cond_value, tempSymtable)) {
Context.top.pushStack();
for (var entry : tempSymtable.entrySet()) {
Context.top.putLocal(entry.getKey(), entry.getValue());
}
var result = match_case.value.execute();
Context.top.dropStackFrame();
return result;
}
var tempSymtable = new HashMap<String, PiccodeValue>();
if (isMatching(match_case.match, cond_value, tempSymtable)) {
Context.top.pushStack();
try {
for (var entry : tempSymtable.entrySet()) {
Context.top.putLocal(entry.getKey(), entry.getValue());
}
return match_case.value.execute();
} finally {
Context.top.dropStackFrame();
}
}
🤖 Prompt for AI Agents
In src/main/java/org/piccode/ast/WhenAst.java around lines 44 to 53, the call to
Context.top.dropStackFrame() is skipped if match_case.value.execute() throws an
exception, causing a stack-frame leak. To fix this, wrap the code between
Context.top.pushStack() and Context.top.dropStackFrame() in a try/finally block,
ensuring dropStackFrame() is always called regardless of exceptions.

@hexaredecimal hexaredecimal merged commit 311c4c8 into main May 20, 2025
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants